<?php
namespace App\Admin\Extensions\Excel;

use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Events\AfterSheet;

class BaseExporter extends ExcelExporter implements WithMapping,WithEvents
{
    protected $fileName = '文件名称.xlsx';
    protected $columns = ['id'=>"ID"];
    protected $columnsWidth = [];
    public function __construct($fileName,$columns,$columnsWidth=[])
    {
        if(strpos($fileName,".xlsx")===false)
        {
            $fileName = $fileName.".xlsx";
        }
        $this->fileName = $fileName;
        $this->columns = $columns;
        $this->columnsWidth = $columnsWidth;
    }
    /**
     * @var \\Model Model
     */
    public function map($row): array
    {
        if(isset($row['st']) && is_numeric($row['st']))
        {
            $row->st = $row->getStatus($row->st);
        }
        if(isset($row['type']) && is_numeric($row['type']))
        {
            $row->type = $row->getType($row->type);
        }
        return $row->toArray();
    }
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event)
            {
                if(count($this->columnsWidth)>0)
                {
                    foreach($this->columnsWidth as $k=>$v)
                    {
                        $event->sheet->getDelegate()->getColumnDimensionByColumn($k+1)->setWidth($v);
                    }
                }
            },
        ];
    }

}